package com.domor.web.controller.system;

import com.domor.common.core.controller.BaseController;
import com.domor.common.core.domain.AjaxResult;
import com.domor.common.utils.ServletUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <h3>登录验证 控制层</h3>
 * @author liyuyang
 * @date 2020/4/23
 **/
@Controller
public class SysLoginController extends BaseController {

    /**
     * 登录页面
     */
    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":1, \"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        return "login";
    }

    /**
     * 登录方法
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe) {
        // 暂时关闭rememberMe功能，开启后会使强退功能失效
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return success();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 无权限页面
     */
    @GetMapping("/403")
    public String noAuth() {
        return "error/403";
    }

}
